package com.liwc.service.impl;

import java.lang.reflect.InvocationTargetException;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.liwc.constant.StatusCode;
import com.liwc.dao.SysMenuMapper;
import com.liwc.dto.MenuDto;
import com.liwc.message.ResponseMessage;
import com.liwc.model.SysMenu;
import com.liwc.model.SysMenuTree;
import com.liwc.service.MenuService;

@Service
public class MenuServiceImpl implements MenuService {

	// log
	private static final Log log = LogFactory.getLog(MenuServiceImpl.class);

	@Autowired
	private SysMenuMapper dao;



	/**
	 * 查询所有
	 */
	@Override
	public PageInfo<SysMenu> findAllMenu(MenuDto dto) {

		// 开始分页
		PageHelper.startPage(dto.getPage(), dto.getRows());

		List<SysMenu> mlist = dao.selectAll(dto);

		PageInfo<SysMenu> pi = new PageInfo<SysMenu>(mlist);

		return pi;
	}



	@Override
	public MenuDto findById(Integer id) {

		if(null == id){
			return new MenuDto();
		}
		
		SysMenu menu = dao.selectByPrimaryKey(id);

		MenuDto dto = new MenuDto();

		try {
			BeanUtils.copyProperties(dto, menu);
		} catch (IllegalAccessException | InvocationTargetException e) {
			e.printStackTrace();
		}

		return dto;
	}

	@Override
	public List<SysMenu> findAllWithChild() {
		return dao.selectAllWithChild();
	}



	@Override
	public ResponseMessage save(SysMenu resource) {
		
		
		if("dir".equals(resource.getMenuType())){
			resource.setMenuLevel(1);
		}else if("page".equals(resource.getMenuType())){
			resource.setMenuLevel(2);
		}
		
		if(null != resource.getId() ){
			dao.updateByPrimaryKeySelective(resource);
			
		}else{
			
			Integer no = dao.selectMaxOrderBy(resource);
			resource.setMenuOrder(no+1);
			dao.insertSelective(resource);
		}
		
		return new ResponseMessage(StatusCode.OK, "保存成功", resource);
	}



	@Override
	public List<SysMenuTree> selectTreeMenu(MenuDto dto) {
		return dao.selectTreeMenu(dto);
	}



	@Override
	public ResponseMessage deleteById(Integer id) {
		dao.deleteByPrimaryKey(id);
		return new ResponseMessage(StatusCode.OK, "删除成功", id);
	}
	
	

}